package display;

/**
 *@author Adam
 */


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class TextBasedDisplayLarge implements Display{
	BonjourService bs;
	RMIServerImpl rmi;
	ConnectSocket SSS;
	String size = "large";

	public TextBasedDisplayLarge() {
	}

	public int displayNumbers(){
		int number = 1;
		try{
			Registry registry = LocateRegistry.getRegistry();
			String[] registryComponents = registry.list();
			for (int i = 0; i < registryComponents.length; i++){
				if(registryComponents[i].startsWith("display")) 
					number++;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return number;
	}

	public void begin(){
		try{
			int num = displayNumbers();
			rmi = new RMIServerImpl("display"+num);
			rmi.begin();
			SSS = new ConnectSocket(1270, "display"+num,size);
			int port = SSS.getPort();
			bs = new BonjourService("display"+num, port);
			bs.registerService();
			SSS.listen();
//			SSS.close();
		} catch(Exception e){
			System.out.println("problem");
			e.printStackTrace();
		}
	}

	public void close(){
		bs.unregisterService();
		rmi.close();
		System.exit(0);
	}

	public static void main(String[] args){
		TextBasedDisplayLarge td = new TextBasedDisplayLarge();
		td.begin();
		while (true){
			System.out.println("Start typing, then press <return>");
			BufferedReader in =	new BufferedReader(new InputStreamReader(System.in));
			String s = null;
			try {
				s = in.readLine();
				System.out.println("Echo: " + s);
				if (s.equals("close")){
					td.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}